% Test program to generate covariance blocks
%
% DESCRIPTION
%   The total dataset comes from a file. The file provides data for
%   different subsets and covariance matrix for every subset are computed.
%
% OUTPUT
%   CovBlocks is a cell array. Each cell contains a covariance matrix for every subset. 
%
%   SampleSizes defines how many samples were used to estimate each covariance
%   matrix and is a measure of reliability for that covariance block.
%
%   StockReturns defines the returns of the stocks computed from the
%   dataset.
%
%   Combinations defines which stocks are involved in each covariance
%   block.
%
%   Sigma is a covariance matrix created using ALL the data.
%
% INPUT
%
%   File is the full name of the file (with extension).

function [CovBlocks, Combinations, SampleSizes, StockReturns] = GetCovBlocks(File),

dataset = load(File);

sr = 100 * (dataset(:, 4:end)-dataset(:, 3:end-1))./dataset(:, 3:end-1);

N = size(dataset,1);
SamplesSizes = size(sr,2); % The first column says the market.

StockReturns = cell(1);
Combinations = cell(1);
for i=1:N,
    if (length(StockReturns) < dataset(i,1)),
        StockReturns{dataset(i,1)} = [];
        Combinations{dataset(i,1)} = [];
    end
    StockReturns{dataset(i,1)} = [StockReturns{dataset(i,1)} sr(i,:)'];
    Combinations{dataset(i,1)} = [Combinations{dataset(i,1)} dataset(i,2)];
end

numCovBlocks = length(StockReturns);

CovBlocks = cell(1);
for i=1:numCovBlocks,
    [Combinations{i}, ind] = sort(Combinations{i});
    StockReturns{i} = StockReturns{i}(:, ind); % sort in ascending order to analyze better
    CovBlocks{i} = cov(StockReturns{i});
    NormalizedCovBlocks{i} = CovBlocks{i};
    
    for j=1:length(ind), 
        NormalizedCovBlocks{i}(j,:) = CovBlocks{i}(j,:)./sqrt((CovBlocks{i}(j,j).*diag(CovBlocks{i})'));
    end
end